<?php
/**
 * Created by PhpStorm.
 * User: wangchaozhen
 * Date: 2018/7/1
 * Time: 11:49
 */
namespace App\Service\Indent;
use App\Common\Fun;
use DB;

class CourierService
{
    /**
     * 获得订单物流信息
     */
    public static function getOrderCourier($order_id)
    {
        return DB::table('lsj_order_courier as a')
            ->leftJoin('lsj_zd_courier as b','a.courier_id','=','b.id')
            ->where('a.order_id',$order_id)
            ->select('a.*','b.code')
            ->first();
    }


    /**
     * 快递鸟接口
     */
    public static function birdApi($code,$courier_code)
    {
        $wuliu_config = config('wuliu');
        $app_id = $wuliu_config['app_id'];
        $app_key = $wuliu_config['app_key'];
        $request_data = json_encode([
            'OrderCode' => '',
            'ShipperCode' => $code,
            'LogisticCode' => $courier_code
        ],JSON_UNESCAPED_UNICODE);

        $datas = array(
            'EBusinessID' => $app_id,
            'RequestType' => '1002',
            'RequestData' => urlencode($request_data) ,
            'DataType' => '2',
        );

        $datas['DataSign'] = urlencode(base64_encode(md5($request_data.$app_key)));

        $result = Fun::sendUrl('post',$wuliu_config['url'],$datas);
        $res_array = json_decode($result);

        if(!is_object($res_array)){
            throw new \Exception('物流接口失败');
        }

        $res_array = (array)$res_array;
        if(!$res_array['Success']){
            if(isset($res_array['Reason'])){
                $error_msg = $res_array['Reason'];
            }else{
                $error_msg = '物流查询失败';
            }
            throw new \Exception($error_msg);
        }

        return $res_array;
    }


    /**
     * 更新物流信息
     */
    public static function changeOrderCourier($order_id,$update_array)
    {
        return DB::table('lsj_order_courier')->where('order_id',$order_id)->update($update_array);
    }
}